<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select style="width:130px" v-model="search_type" filterable @change="searchTypeChange">
            <el-option v-for="item in searchList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="search_font" :maxlength="30" :placeholder="searchPlaceholder" @keyup.enter.native="searchClick"></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border fit size="small">
        <el-table-column align="center" label='序号' width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label='姓名' prop="nick"></el-table-column>
        <el-table-column align="center" label="用户名" prop="name"></el-table-column>
        <el-table-column align="center" label="手机" prop="phone"></el-table-column>
        <el-table-column align="center" label="性别" prop="sex">
          <template slot-scope="scope">
            {{scope.row.sex==1?'男':scope.row.sex==2?'女':scope.row.sex==3?'保密':'未设置'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建日期" prop="registration"></el-table-column>
        <el-table-column align="center" label="最后登录" prop="lastlogin"></el-table-column>
        <el-table-column align="center" label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="addEditClick(scope.row.id,scope.$index)"></el-button>
            <router-link :to="{name:'setting/auth_user_store',params :{clerk_id:scope.row.id,routerflag:1}}">
              <el-button type="primary" size="mini">
                <svg-icon icon-class="key" />
              </el-button>
            </router-link>
            <el-button type="primary" size="mini" @click="accreditHouseClick(scope.row.id,scope.$index)">
              <svg-icon icon-class="store" />
            </el-button>
            <el-button style="margin-left:0" type="danger" icon="el-icon-delete" size="mini" @click="delClick(scope.row.id,scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 用户信息弹框 -->
    <el-dialog :close-on-click-modal="false" width="360px" :title="dialogTitle" :visible.sync="addEditDialog" @close="callOf('saveForm')">
      <el-form :inline="true" :model="saveForm" ref="saveForm" :rules="rules" size="small">
        <b>登录信息</b>
        <br>
        <el-form-item label="　用户名" prop="name">
          <el-input v-model="saveForm.name" class="w200"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input type="number" onmousewheel="return false;" v-model="saveForm.phone" class="w200"></el-input>
        </el-form-item>
        <el-form-item label="　　密码" prop="password">
          <el-input type="password" v-model="saveForm.password" class="w200"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input type="password" v-model="saveForm.password2" class="w200"></el-input>
        </el-form-item>
        <br>
        <b>用户信息</b>
        <br>
        <el-form-item label="　　姓名" prop="nick">
          <el-input v-model="saveForm.nick" class="w200"></el-input>
        </el-form-item>
        <el-form-item label=". 　　性别">
          <el-select placeholder="选择性别" v-model="saveForm.sex">
            <el-option v-for="item in sex" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=". 　　地址">
          <el-input v-model="saveForm.address" class="w200"></el-input>
        </el-form-item>
        <el-form-item label=". 　　邮箱">
          <el-input v-model="saveForm.email" class="w200"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveClick('saveForm')" size="small">保 存</el-button>
        &nbsp;
      </div>
    </el-dialog>

    <!-- 授权仓库 -->
    <el-dialog :close-on-click-modal="false" width="30%" title="授权仓库列表" :visible.sync="houseDialog" append-to-body>
      <el-form :inline="true" :model="addHouseForm" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select placeholder="选择仓库" v-model="addHouseForm.house_id" filterable>
            <el-option v-for="item in houseList" :key="item.house_id" :label="item.name" :value="item.house_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addHouseClick" size="small">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="haveHouseList" border size="small">
        <el-table-column align="center" property="house_name" label="仓库名称"></el-table-column>
        <el-table-column align="center" label="操作" width="80">
          <template slot-scope="scope">
            <el-button type="danger" @click="houseDelClick(scope.row.id,scope.$index)" icon="el-icon-delete" size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 邀请用户加入组织 -->
    <el-dialog :close-on-click-modal="false" width="25%" title="添加用户" :visible.sync="inviteDialog" append-to-body>
      <el-form :inline="true" size="small" style="display：inline-block;text-align:center;">
        <el-form-item>
          <el-input type="" placeholder="请输入手机号码" v-model="inviteMobile" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="inviteUserAdd" size="small">添加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber">
      </el-pagination>
      <el-button class="pull-right" type="primary" size="small" @click="addEditClick()">新增用户</el-button>
      <el-button class="pull-right" type="primary" size="small" @click="inviteUserClick()">添加用户</el-button>
    </div>
  </div>
</template>

<script>
import { getList, getPage, editUser, createUser, getUser, del, houseList, haveHouseList, addHouse, houseDel, inviteUser } from '@/api/setting/user_list';
import md5 from 'js-md5';
import { isvalidUsername, isvalidPassword, mobile } from '@/utils/validate';
import { JSEncrypt } from 'jsencrypt';
export default {
  data() {
    const validateUserName = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('2-25位 字母+数字,不包含特殊字符!'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!isvalidPassword(value)) {
        callback(new Error('长度6-12位字符，不能纯数字或字母!'));
      } else {
        callback();
      }
    };
    const validateMobile = (rule, value, callback) => {
      if (!mobile(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    return {
      public_key:
        '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3//sR2tXw0wrC2DySx8vNGlqt3Y7ldU9+LBLI6e1KS5lfc5jlTGF7KBTSkCHBM3ouEHWqp1ZJ85iJe59aF5gIB2klBd6h4wrbbHA2XE1sq21ykja/Gqx7/IRia3zQfxGv/qEkyGOx+XALVoOlZqDwh76o2n1vP1D+tD3amHsK7QIDAQAB-----END PUBLIC KEY-----',
      sex: [{ id: '0', name: '未设置' }, { id: '1', name: '男' }, { id: '2', name: '女' }, { id: '3', name: '保密' }],
      dialogTitle: '编辑用户信息',
      url: '',
      addEditDialog: false,
      houseDialog: false,
      inviteDialog: false,
      inviteMobile: '',
      list: null,
      listLoading: false,
      currentPage: 1,
      totalDataNumber: 0,
      search_font: '',
      search_type: 1,
      formInline: {
        nick: '',
        phone: ''
      },
      houseList: [],
      haveHouseList: [],
      searchPlaceholder: '请输入姓名',
      searchList: [{ id: 1, name: '姓名' }, { id: 2, name: '手机号' }],
      addHouseForm: {
        house_id: '',
        clerk_id: '',
        clerk_house_id: 0
      },
      saveForm: {
        id: '',
        nick: '',
        name: '',
        sex: '',
        phone: '',
        password: '',
        password2: '',
        address: '',
        email: '',
        pwd_len: ''
      },
      rules: {
        nick: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
        name: [{ required: true, trigger: 'blur', validator: validateUserName }],
        sex: [{ required: true, trigger: 'blur', validator: validateUserName }],
        phone: [{ required: true, trigger: 'blur', validator: validateMobile }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        password2: [{ required: true, trigger: 'blur', validator: validatePassword }]
      }
    };
  },
  watch: {
    $route(to, from) {
      if (this.$route.params.nick) {
        this.formInline.nick = this.$route.params.nick;
        this.searchClick();
        this.getHouseList();
      }
    }
  },
  created() {
    this.formInline.nick = this.$route.params.nick;
    this.searchClick();
    this.getHouseList();
  },
  methods: {
    searchTypeChange(i) {
      if (i == 1) {
        this.searchPlaceholder = '请输入姓名';
      } else {
        this.searchPlaceholder = '请输入手机号';
      }
      this.search_font = '';
    },
    accreditHouseClick(id) {
      this.addHouseForm.clerk_id = id;
      haveHouseList({ clerk_id: id }).then(response => {
        this.haveHouseList = response;
        this.houseDialog = true;
      });
    },
    houseDelClick(id, index) {
      houseDel({ clerk_house_id: id }).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        if (response.code == 1) {
          this.haveHouseList.splice(index, 1);
        }
      });
    },
    addHouseClick() {
      console.log(this.addHouseForm);
      if (this.addHouseForm.house_id === '') {
        this.$message({ type: 'error', message: '请选择仓库' });
        return;
      }
      addHouse(this.addHouseForm).then(response => {
        this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
        if (response.code == 1) {
          haveHouseList({ clerk_id: this.addHouseForm.clerk_id }).then(response => {
            this.haveHouseList = response;
          });
        }
        // this.haveHouseList = response
        // this.houseDialog = true
      });
    },
    getHouseList() {
      houseList({ category_id: 143 }).then(response => {
        this.houseList = response;
      });
    },
    // 保存按钮
    saveClick(formName) {
      this.saveForm.pwd_len = this.saveForm.password.length;
      if (this.saveForm.password != this.saveForm.password2) {
        this.$message({ type: 'error', message: '两次密码不一致，请重新输入密码!' });
        this.saveForm.password = '';
        this.saveForm.password2 = '';
        return;
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let encryptor = new JSEncrypt();
          encryptor.setPublicKey(this.public_key);
          this.saveForm.password = encryptor.encrypt(md5(this.saveForm.password));
          this.saveForm.password2 = null;
          if(this.url == '/User/edit'){
            editUser(this.saveForm).then(response => {
              this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
              if (response.code == 1) {
                this.handleCurrentChange(this.currentPage);
                this.addEditDialog = false;
              }
            });
          }else{
            createUser(this.saveForm).then(response => {
            this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
            if (response.code == 1) {
              this.currentPage = Math.ceil((this.totalDataNumber + 1) / 20 - 1);
              this.fetchData();
              this.addEditDialog = false;
            }
          });
          }
          
        }
      });
    },
    // 邀请用户加入
    inviteUserAdd() {
      if (!this.inviteMobile || !mobile(this.inviteMobile)) {
        this.$message({ type: 'error', message: '请输入正确的手机号码!' });
        return;
      }
      inviteUser({ phone: this.inviteMobile }).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message+'，请手动刷新列表'
        });
        this.inviteDialog = false;
      });
    },
    // 邀请用户加入企业：展示弹窗
    inviteUserClick() {
      this.inviteDialog = true;
      this.inviteMobile = '';
    },
    // 新增或编辑用户按钮
    addEditClick(id, index) {
      this.addEditDialog = true;
      this.dialogTitle = id ? '编辑用户信息' : '新增用户';
      console.log(this.rules.password[0].required);
      this.url = id ? '/User/edit' : '/User/create';
      if (id) {
        getUser({ id: id }).then(response => {
          this.saveForm = {
            id: id,
            nick: response.nick,
            name: response.name,
            sex: response.sex,
            phone: response.phone,
            password: '',
            password2: '',
            address: response.address,
            email: response.email,
            pwd_len: ''
          };
        });
      }
    },
    // 删除按钮
    delClick(id, index) {
      this.$confirm('此操作删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id: id }).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    // 搜索
    searchClick() {
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      if (this.search_type == 1) {
        this.formInline.nick = this.search_font;
        this.formInline.phone = '';
      } else {
        this.formInline.nick = '';
        this.formInline.phone = this.search_font;
      }
      getPage(this.formInline)
        .then(response => {
          this.totalDataNumber = response * 20;
          getList(this.formInline).then(response => {
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then(response => {
        this.list = response;
        this.listLoading = false;
      });
    },
    //关闭弹框重置
    callOf(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>